package com.seh.contentcenter.controller;

import com.seh.contentcenter.domain.JsonResult;
import com.seh.contentcenter.entity.Post;
import com.seh.contentcenter.service.PostService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
    /**
     * 时间格式化
     */
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 保存图片路径，自动从yml文件中获取数据
     */
    @Value("${file-save-path}")
    private String fileSavePath;

    @Autowired
    private PostService postService;

    @GetMapping(path = "/upload")
    public JsonResult uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        //1.后半段目录：  2023/06/15
        String directory = simpleDateFormat.format(new Date());
        /**
         *  2.文件保存目录  E:/images/2023/06/15
         *  如果目录不存在，则创建
         */
        File dir = new File(fileSavePath + directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        log.info("图片上传，保存位置：" + fileSavePath + directory);
        //3.给文件重新设置一个名字
        //后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
        //4.创建这个新文件
        File newFile = new File(fileSavePath + directory + "/" + newFileName);
        //5.复制操作
        try {
            file.transferTo(newFile);
            //协议 :// ip地址 ：端口号 / 文件目录(/images/2023/06/1/xxx.jpg)
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/picture_test/" + directory + "/" + newFileName;
            log.info("图片上传，访问URL：" + url);
            return JsonResult.builder().data(url).message("上传成功！").code("1").build();
        } catch (IOException e) {
            return JsonResult.builder().data(null).message("IO异常！").code("-1").build();
        }
    }

    /**
     * 前端发送多个图片，并将图片存入到本地，并打印地址
     *
     * @param files
     * @param request
     * @return
     */
    @PostMapping("/uploads")
    public List<JsonResult> uploadMultipleFiles(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
        List<JsonResult> results = new ArrayList<>();
        for (MultipartFile file : files) {
            //1.后半段目录：  2023/06/15
            String directory = simpleDateFormat.format(new Date());
            /**
             *  2.文件保存目录  E:/images/2023/06/15
             *  如果目录不存在，则创建
             */
            File dir = new File(fileSavePath + directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            log.info("图片上传，保存位置：" + fileSavePath + directory);
            //3.给文件重新设置一个名字
            //后缀
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            //4.创建这个新文件
            File newFile = new File(fileSavePath + directory + "/" + newFileName);
            //5.复制操作
            try {
                file.transferTo(newFile);
                //协议 :// ip地址 ：端口号 / 文件目录(/images/2023/06/15xxx.jpg)
                String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/picture_test/" + directory + "/" + newFileName;
                log.info("图片上传，访问URL：" + url);
                JsonResult result = JsonResult.builder().data(url).message("上传成功！").code("1").build();
                results.add(result);
            } catch (IOException e) {
                JsonResult result = JsonResult.builder().data(null).message("IO异常！").code("-1").build();
                results.add(result);
            }
        }
        return results;
    }

    /**
     * 新建帖子
     * 前端既发送文字，又发送图片
     *
     * @param files
     * @param request
     * @return
     */
    @PostMapping("/uploadsMultiple")
    public List<JsonResult> uploadMultipleFilesAndContent(@RequestParam("title") String title,
                                                          @RequestParam("content") String content,
                                                          @RequestParam("authorId") Integer authorId,
                                                          @RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
        List<JsonResult> results = new ArrayList<>();
        Post post = new Post();
        post.setTitle(title);
        post.setContent(content);
        post.setAuthorId(authorId);
        for (MultipartFile file : files) {
            //1.后半段目录：  2023/06/15
            String directory = simpleDateFormat.format(new Date());
            /**
             *  2.文件保存目录  E:/images/2023/06/15
             *  如果目录不存在，则创建
             */
            File dir = new File(fileSavePath + directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            log.info("图片上传，保存位置：" + fileSavePath + directory);
            //3.给文件重新设置一个名字
            //后缀
            //String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + ".png";
            //4.创建这个新文件
            File newFile = new File(fileSavePath + directory + "/" + newFileName);
            //5.复制操作
            try {
                file.transferTo(newFile);
                //协议 :// ip地址 ：端口号 / 文件目录(/images/2023/06/15/xxx.jpg)
                String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/picture_test/" + directory + "/" + newFileName;
                if (post.getPicPath() != null) {
                    String picPath = post.getPicPath();
                    post.setPicPath(picPath + ";" + url);
                } else {
                    post.setPicPath(url);
                }
                log.info("图片上传，访问URL：" + url);
                JsonResult result = JsonResult.builder().data(url).message("上传成功！").code("1").title(title).content(content).build();
                results.add(result);
            } catch (IOException e) {
                JsonResult result = JsonResult.builder().data(null).message("IO异常！").code("-1").build();
                results.add(result);
            }
        }
        //将帖子存入数据库中
        postService.addPost(post);
        return results;
    }
}


















